"""
下载器类,他可以调用解析器来进行解析和下载
"""

import requests
from bilibili import Bilibili
from btools import FileTools
from threading import Thread

from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile
from PySide2.QtWidgets import QFileDialog


class Downloader:
    """
    下载器
    """

    def __init__(self):
        self.request = requests
        self.fts = FileTools()
        ui_path = self.fts.getpath('bdownloader.ui')
        file = QFile(ui_path)  # 文件所在路径
        file.open(QFile.ReadOnly)
        self.ui = QUiLoader().load(file)
        self.analysiser = None
        self.qfd = QFileDialog(self.ui)

        # 平台类型
        self.platform = self.ui.combobox_platform.currentText()
        # 地址类型
        self.addrtype = self.ui.combobox_addrtype.currentText()
        self.ui.button_analysis.clicked.connect(self.analysis_handle)
        self.ui.setting_pushbutton.clicked.connect(self.setting_handle)
        self.ui.button_download.clicked.connect(self.download_handle)
        self.download_path = ''

    def setting_handle(self):
        self.download_path = self.qfd.getExistingDirectory(self.ui, "下载文件的保存路径:")  # 选择目录，返回选中的路径
        self.ui.label_dlpath.setText("下载路径:\n" + self.download_path)

    def analysis_handle(self):
        """
        点击解析按钮触发
        """
        if self.platform == 'B站':
            url = self.ui.lineedit_addr_source.text()
            self.analysiser = Bilibili(url, self.ui)
            self.analysiser.analysis()

    def download_handle(self):
        """
        点击下载按钮触发
        """
        if not self.download_path:
            self.download_path = self.qfd.getExistingDirectory(self.ui, "下载文件的保存路径:")  # 选择目录，返回选中的路径
            self.ui.label_dlpath.setText("下载路径:\n" + self.download_path)
        if self.download_path:
            t = Thread(target=self.analysiser.download, args=(self.download_path,))
            t.start()
